import { createSlice } from "@reduxjs/toolkit";
// 导入本地存储工具函数，用于操作 localStorage
import { deleteData, getData, saveData } from "../../utils/localStorage";

// 初始化用户信息的函数：从 localStorage 尝试获取 currentUser
const initUser = () => {
  const currentUser = getData("currentUser");
  if (currentUser) {
    return currentUser;
  }
  return null;
};

// 初始化 token 的函数：从 localStorage 尝试获取 token
const initToken = () => {
  const token = getData("token");
  if (token) {
    return token;
  }
  return null;
};

// 定义 settingSlice 的初始状态
let initialState = {
  ...initUser(), // 扩展 initUser 返回的用户信息
  token: initToken(), // 初始化 token
  errors: null,
  currentUser: initUser(),
};
// let initialState = {
//   currentUser: initUser(),
//   token: initToken(),
//   errors: null,
// };

// 创建 settingSlice
export const settingSlice = createSlice({
  name: "setting",
  initialState,
  reducers: {
    // 处理用户登出的 reducer
    userLogout() {
      // 从 localStorage 删除 currentUser 和 token
      deleteData("currentUser");
      deleteData("token");
    },
    settingFileUpdate(state, action) {
      const key = action.payload.key;
      const value = action.payload.value;
      state[key] = value;
    },
    userUpdate(state, action) {
      if (action.payload.status === 1) {
        const currentUser = action.payload.data;
        console.log(currentUser);

        const token = action.payload.data.token;
        saveData("currentUser", currentUser);
        saveData("token", token);
        state = { ...state, ...initUser() };
      } else {
        state.errors = action.payload.message;
      }
    },
    onUnload(state) {
      return {
        ...initUser(),
        token: initToken(),
        errors: null,
        currentUser: initUser(),
      };
    },
  },
});

// 导出 userLogout action 创建函数，供组件中 dispatch 使用
export const { userLogout, settingFileUpdate, userUpdate, onUnload } =
  settingSlice.actions;

// 导出 settingSlice 的 reducer，用于配置 Redux store
export default settingSlice.reducer;
